
/**   
*    
* 项目名称：a_yongan   
* 类名称：OutsourcingInServiceImpl   
* 类描述：   
* 创建人：liubo   
* 创建时间：2018年6月30日 上午10:59:50    
* 修改时间：2018年6月30日 上午10:59:50   
* 修改备注：   
* @version    
*    
*/
package com.yongan.purchase.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import com.yongan.purchase.dao.PurchaseDao;
import com.yongan.purchase.dao.PurchaseGoodsDetailsDao;
import com.yongan.purchase.dao.PurchaseInDao;
import com.yongan.purchase.entity.PurchaseGoodsDetails;
import com.yongan.purchase.entity.PurchaseIn;
import com.yongan.purchase.service.PurchaseInService;
import com.yongan.user.enums.UserStatEnum;
import com.yongan.user.exception.UserException;
import com.yongan.util.Execution;
import com.yongan.warehouse.dao.GoodsinformationDao;

/**
 * @author liubo
 *
 */
@Service
public class PurchaseInServiceImpl implements PurchaseInService{

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private PurchaseDao purchaseDao;
	@Autowired
	private PurchaseInDao purchaseInDao;
	@Autowired
	private PurchaseGoodsDetailsDao purchaseGoodsDetailsDao;
	@Autowired
	private GoodsinformationDao goodsinformationDao;
	private final String slat = "dsjdajsdkHJJHAJAKdsd921e0p12*DAe#@$@!qew";
	@Override
	public List<PurchaseIn> getPurchaseInList(int offset, int limit) {
		return purchaseInDao.queryAll(offset, limit);
	}

	
	@Override
	public PurchaseIn getPurchaseInById(String purchaseinId) {
		// TODO 自动生成的方法存根
		PurchaseIn purchaseIn = purchaseInDao.queryById(purchaseinId);
		purchaseIn.setDetails(purchaseGoodsDetailsDao.queryAllByTopId(purchaseIn.getPurchasedId()));
		purchaseIn.setProcurement(purchaseDao.queryById(purchaseIn.getPurchasedId()));
		return purchaseIn;
	}

	

	@Override
	@Transactional
	public Execution executePurchaseIn(PurchaseIn purchaseIn,
			String purchaseinId, String md5) throws UserException {
		if(md5 == null || !md5.equals(getMD5(purchaseinId))){
			//throw new UserException("user data rewrite");
		}
		List<PurchaseGoodsDetails> details =null;
		try{
			Boolean updateDetailsRkslIs = false;
			if(purchaseIn == null){//删除
				PurchaseIn readDell = purchaseInDao.queryById(purchaseinId);
				details = purchaseGoodsDetailsDao.queryAllByTopId(readDell.getPurchasedId());
				//details = readDell.getDetails();
				if(!(details==null)){
					for(PurchaseGoodsDetails goodDetails:details){
						//首先将detail中的入库数量滞空
						int updateDetailsRksl = purchaseGoodsDetailsDao.updateDetailsRksl(goodDetails.getpurchasegoodsdetailsId(),"");
						if(updateDetailsRksl<=0){
							updateDetailsRkslIs = true;//标识滞空detail中的入库数量失败
						}
						//其次，减去商品中已新增的数量
						reduceNumber(goodDetails, "reduce");
					}
				}
				//更改采购订单中可选择的标识
				int changeCount = purchaseDao.isChecked(readDell.getPurchasedId(),"false");
				//删除采购入库单
				int deleteCount = purchaseInDao.deletePurchaseIn(purchaseinId);
				
				if(deleteCount<=0 & changeCount<=0 & updateDetailsRkslIs){
					throw new UserException("delete failed");
				}else{
					return new Execution(purchaseinId, UserStatEnum.SUCCESS);
				}
			}else if((purchaseinId.equals(""))){//新增
				details = purchaseIn.getDetails();
				int goodDetailsaddcount = 1;
				if(!(details==null)){
					for(PurchaseGoodsDetails goodDetails:details){
						//System.out.println(goodDetails.getpurchasegoodsdetailsId()+"==="+goodDetails.getPurchasegoodsdetailsRksl());
						int updateDetailsRksl = purchaseGoodsDetailsDao.updateDetailsRksl(goodDetails.getpurchasegoodsdetailsId(),goodDetails.getPurchasegoodsdetailsRksl());
						if(updateDetailsRksl<=0){
							updateDetailsRkslIs = true;//标识滞空detail中的入库数量失败
						}
						reduceNumber(goodDetails, "add");
					}
				}
				int changeCount = purchaseDao.isChecked(purchaseIn.getPurchasedId(),"true");
				int addCount = purchaseInDao.insertPurchaseIn(purchaseIn);
				if(addCount<=0 & goodDetailsaddcount<=0 & updateDetailsRkslIs & changeCount<=0){
					throw new UserException("add failed");
				}else{
					return new Execution(purchaseIn.getPurchaseId(), UserStatEnum.SUCCESS);
				}
			}else if(!(purchaseinId.equals(""))){//修改
				List<PurchaseGoodsDetails> oldList = purchaseGoodsDetailsDao.queryAllByTopId(purchaseIn.getPurchasedId());
			//	List<String> newList = new ArrayList<String>();
				//String[] newList;
				details = purchaseIn.getDetails();
				if (oldList != null) {
					for (PurchaseGoodsDetails old : oldList) {
						// 减去旧列表在库存中的数量
						reduceNumber(old, "reduce");
					}
				}
				//int goodDetailscount = 1;
				if(!(details==null)){
					for(PurchaseGoodsDetails goodDetails:details){
						int updateDetailsRksl = purchaseGoodsDetailsDao.updateDetailsRksl(goodDetails.getpurchasegoodsdetailsId(),goodDetails.getPurchasegoodsdetailsRksl());
						if(updateDetailsRksl<=0){
							updateDetailsRkslIs = true;//标识滞空detail中的入库数量失败
						}
						//加上新保存的列表
						reduceNumber(goodDetails, "add");
					}
				}

				int updateCount = purchaseInDao.updatePurchaseIn(purchaseIn);
				if(updateCount<=0 & updateDetailsRkslIs){
					throw new UserException("update failed");
				}else{
					return new Execution(purchaseinId, UserStatEnum.SUCCESS);
				}
			}else{
				throw new UserException("parameter error");
			}
		}catch(Exception e){
			logger.error(e.getMessage(),e);
			throw new UserException("inner error:"+e.getMessage());
		}
	}

	
	@Override
	public int getCount() {
		// TODO 自动生成的方法存根
		return purchaseInDao.queryCount();
	}
	
	private String getMD5(String Id){
		String base = Id + "/" + slat;
		String md5 = DigestUtils.md5DigestAsHex(base.getBytes());
		return md5;
	}


	public PurchaseInServiceImpl() {
		super();
		// TODO 自动生成的构造函数存根
	}


	public int reduceNumber(PurchaseGoodsDetails igd,  String type){
		return goodsinformationDao.reduceNumber(igd.getpurchasegoodsdetailsHpbm()
				, type, Integer.parseInt(igd.getpurchasegoodsdetailsHpsl())
				, Integer.parseInt(igd.getPurchasegoodsdetailsRksl()));
	}
	public static void main(String[] args) {
		//6ae45642-49ca-428c-941d-6d1ed0b98f37===2
		PurchaseInServiceImpl pi = new PurchaseInServiceImpl();
		pi.purchaseGoodsDetailsDao.updateDetailsRksl("6ae45642-49ca-428c-941d-6d1ed0b98f37", "2");
	}
}
